const express = require("express");
const app = express();
var http = require("http");


/* 导入xml2js */
/* 导入两个对象 */
/* 1、导入 */
var xml2js = require('xml2js');
/* 2、创建xml->js对象 */
var parser = new xml2js.Parser({
    explicitArray: false
});
/* 3、创建 js->xml对象 */
var builder = new xml2js.Builder({
    rootName: "xml",
    cdata: true,
    headless: true
})

app.get('/', (req, res) => {
    console.log(req.query, 666);
    /*  res.send('请求成功了'); */
    res.send(req.query.echostr);
});
app.post('/', (req, res) => {
    /* 获取数据  数据流事件监听 */
    // var bufferList = null;
    // req.on("data", function (buffer) {
    //     bufferList += buffer
    // })
    // req.on("end", function () {
    //     console.log(bufferList, 88)

    var bufferList = [];
    req.on("data", function (buffer) {
        bufferList.push(buffer);
    })
    req.on("end", function () {
        var result = Buffer.concat(bufferList);
        parser.parseString(result.toString(), (err, msgObj) => {
            console.log(msgObj, 66);
            var msg = "";

            var data = JSON.stringify({
                'key': 'a98d061f25ae4e308062ba3bff511736',
                'info': '好迪真好',
                'userid': '123456'
            });

            var req = http.request({
                method: "post",
                host: "www.tuling123.com",
                protocol: "http:",
                post: "80",
                path: "/openapi/api",
                headers: {
                    "Content-Type": "application/json",
                    "Content-Length": Buffer.byteLength(data)
                }
            }, function (response) {
                var bufferList_r = [];
                response.on("data", function (buffer) {
                    bufferList_r.push(buffer);
                });

                response.on("end", function () {
                    var result_r = Buffer.concat(bufferList_r);
                    console.log(result_r.toString());

                    /* result就是图灵机器人返回来的消息 */
                    msg = JSON.parse(result_r).text;
                    console.log(msg, 5566);

                    /* 将机器人的消息返回微信，微信再返回给用户 */
                    var returnMsg = {
                        ToUserName: msgObj.xml.FromUserName, //开发者微信号
                        FromUserName: msgObj.xml.ToUserName, //发送方帐号（一个OpenID）
                        CreateTime: +new Date(),
                        MsgType: 'text',
                        Content: msg,
                    };
                    /* 响应给用户 */
                    res.send(builder.buildObject(returnMsg));
                })
            });
            req.write(data);
        });
    })
})
app.listen(80, () => {
    console.log("http://echo.free.idcfengye.com");
})



// /* 导入xml2js */
// /* 导入两个对象 */
// /* 1、导入 */
// var xml2js = require('xml2js');
// /* 2、创建xml->js对象 */
// var parser = new xml2js.Parser({
//     explicitArray: false
// });
// /* 3、创建 js->xml对象 */
// var builder = new xml2js.Builder({
//     rootName: "xml",
//     cdata: true,
//     headless: true
// })

// /* xml转换成js对象 */
// var  str=`<xml><ToUserName><![CDATA[gh_3ec8e236dc1c]]></ToUserName>
// <FromUserName><![CDATA[o13wWwXHgPZHj5Oz_cEfAD154Uec]]></FromUserName>
// <CreateTime>1554463778</CreateTime>
// <MsgType><![CDATA[text]]></MsgType>
// <Content><![CDATA[，]]></Content>
// <MsgId>22254566937443931</MsgId>
// </xml>`;

// /* 4、调用parser 将xml数据转成js对象 */
// parser.parseString(str.toString(), (err, msgObj) => {
//     console.log(msgObj,66);
// });

// /* 5、调用bulider 将js对象转对象换成xml数据*/
// var obj = {
//     name: "小明",
//     age: 18
// }

// var result = builder.buildObject(obj);
// console.log(result,77);